<template>
	<div class="main-wrap">
		<!-- 分类 -->
		<CategoryOne />
		<!-- banner -->
		<BannerPart />
		<!-- 列表 -->
		<GoodsList :proList="proList" />
		<!-- 列表数据不能在组件内请求，需要在本页面请求到数据后，传递给子组件 -->
		<!-- 加载提示 -->
		<div class="loading">{{ loadMsg }}</div>
	</div>
</template>
<script>
import CategoryOne from "@/components/CategoryOne.vue";
import BannerPart from "./BannerPart.vue";
import GoodsList from "@/components/goods/GoodsList.vue";
// 导入请求列表函数
import { getGoodList } from "@/api";
export default {
	name: "HomePage",
	data() {
		return {
			proList: [],
			pageNum: 1,
			loading: false, //是否正在加载;节流阀
			loadMsg: "数据加载中···",
		};
	},
	components: {
		CategoryOne,
		BannerPart,
		GoodsList,
	},
	created() {
		this.getList();
	},
	mounted() {
		// 添加滚动监听
		window.addEventListener("scroll", this.bindScroll.bind(this));
	},
	destroyed() {
		/** 组件销毁时，需手动清除window事件监听，否则可能会影响到其他页面的window监听 */
		this.removeScroll();
	},
	methods: {
		// 滚动监听程序
		bindScroll() {
			/* 判断触底，增加页码，调取数据 */
			// 如果正在加载数据，不进行操作。实现节流
			if (this.loading) return;

			// 网页高度
			let pageHeight = document.documentElement.scrollHeight;
			// 窗口高度
			let winHeight = window.innerHeight;
			// 滚动举例
			let sTop = document.documentElement.scrollTop || document.body.scrollTop;

			// console.log(pageHeight, winHeight, sTop);
			// console.log(pageHeight - winHeight - sTop);
			if (
				pageHeight - winHeight - sTop < 10 &&
				this.loadMsg == "数据加载中···"
			) {
				// console.log("触底");
				this.loading = true; //正在加载中
				this.pageNum++;
				// console.log(this.pageNum);
				// 加载新页码数据
				this.getList().then(() => {
					this.loading = false; //数据请求结束后,关闭正在加载中
				});
			}
		},
		// 清除滚动监听
		removeScroll() {
			window.removeEventListener("scroll", this.bindScroll);
		},

		async getList() {
			// console.log(this.pageNum);
			let result = await getGoodList({ page: this.pageNum });
			// console.log(result);
			if (result.length > 0) {
				this.proList.push(...result);
			} else {
				this.loading = false;
				this.loadMsg = "没有了";
			}
		},
	},
};
</script>
<style scoped lang="scss">
.loading {
	text-align: center;
	color: #111;
}
</style>
